package com.weixing.mall.provider.erp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.utils.EnvUtil;
import com.weixing.mall.provider.api.erp.entity.InDepot;
import com.weixing.mall.provider.api.erp.entity.OutDepot;
import com.weixing.mall.provider.api.erp.entity.StyleInfo;
import com.weixing.mall.provider.api.erp.entity.StyleSkuInfo;
import com.weixing.mall.provider.api.erp.query.ErpRequestParams;
import com.weixing.mall.provider.api.erp.query.SkuQuery;
import com.weixing.mall.provider.api.erp.query.StyleQuery;
import com.weixing.mall.provider.api.erp.vo.ResultInDepotVo;
import com.weixing.mall.provider.api.erp.vo.ResultOutDepotVo;
import com.weixing.mall.provider.api.erp.vo.ResultSkuInfoVo;
import com.weixing.mall.provider.api.erp.vo.ResultStyleInfoVo;
import com.weixing.mall.provider.model.domain.Category;
import com.weixing.mall.provider.model.domain.Goods;
import com.weixing.mall.provider.model.domain.Product;
import com.weixing.mall.provider.model.domain.SpecValue;
import com.weixing.mall.provider.model.enums.GoodsFromEnum;
import com.weixing.mall.provider.model.enums.GoodsStateEnum;
import com.weixing.mall.provider.model.vo.SpecValueVo;
import com.weixing.mall.provider.service.*;
import jodd.util.StringUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author c
 * @date 2020-4-12
 * @Description ERP接口
 */
@Service
public class ErpService {
    //授权码
    private final static String access_token = "123456";
    private final static String erpServiceAddress = "120.79.73.252:8091";
    //API接口访问路径 （款式资料分页查询）
    private final static String styleUrl = "/api/Style/StyleInfoByPage";
    //API接口访问路径  (SKU库存分页查询）
    private final static String skuDepotUrl = "/api/Stock/DepotSkuStockByPage";
    //API接口访问路径  （商品出库单接口）
    private final static String outDepotUrl = "/api/Outdepot/AddOutDepot";
    //API接口访问路径  （商品入库单接口）
    private final static String inDepotUrl = "/api/Indepot/AddInDepot";

    /**
     * 颜色库错误信息模板
     */
    private static final String COLOR_ERR_MSG = "颜色库未查找到对应的erp颜色编码，{}:{}";
    /**
     * 尺码库错误信息模板
     */
    private static final String SIZE_ERR_MSG = "尺码库未查找到对应的erp尺码编码，{}:{}";
    /**
     * 类目错误信息模板
     */
    private static final String CAT_ERR_MSG = "未找到与erp对应的商品类目，{}:{}";
    /**
     * 类目不匹配信息模板
     */
    private static final String CAT_PATH_ERR_MSG = "erp类目结构与系统类目结构不匹配；erp类目结构{}，系统目录结构{}";

    /**
     * 颜色id
     */
    private static final long COLOR_ID = 1L;
    /**
     * 尺码id
     */
    private static final long SIZE_ID = 2L;

    /**
     * 类目等级：一级
     */
    private static final int CAT_LV_1 = 1;
    /**
     * 类目等级：二级
     */
    private static final int CAT_LV_2 = 2;
    /**
     * 类目等级：三级
     */
    private static final int CAT_LV_3 = 3;

    /**
     * 分页大小
     */
    private static final int PAGE_SIZE = 100;

    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISpecValueService specValueService;
    @Autowired
    private IProductService productService;

    @Autowired
    private IGoodsImgService goodsImgService;

    /**
     * 1.款式资料分页查询
     * A.参数：分页参数
     * B.返回：款式主资料(包括编码、名称、款式大类、款式小类、原价、售价等)和款式明细资料(包括SKU、颜色、尺码信息等)
     */
    public Result<ResultStyleInfoVo> selectStyleInfoByPage(StyleQuery styleQuery) {
        String result = HttpRequest.post(erpServiceAddress + styleUrl)
                .body(JSONUtil.toJsonStr(new ErpRequestParams(access_token, styleQuery)))
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("success") == 1) {
            ResultStyleInfoVo resultVo = JSONUtil.toBean(jsonObject.getStr("obj"), ResultStyleInfoVo.class);
            return ResultUtil.success(resultVo);
        }
        return ResultUtil.error(jsonObject.getStr("message"));
    }

    /**
     * 2.SKU库存分页查询
     * A.参数：分页参数，按SKU分页
     * B.返回SKU、款式编码、颜色、尺码、目前库存、可配库存
     */
    public Result<ResultSkuInfoVo> selectDepotSkuStockByPage(SkuQuery skuQuery) {
        //System.out.println(JSONUtil.toJsonStr(new ErpRequestParams(access_token, skuQuery)));
        String result = HttpRequest.post(erpServiceAddress + skuDepotUrl)
                .body(JSONUtil.toJsonStr(new ErpRequestParams(access_token, skuQuery)))
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("success") == 1) {
            ResultSkuInfoVo resultVo = JSONUtil.toBean(jsonObject.getStr("obj"), ResultSkuInfoVo.class);
            return ResultUtil.success(resultVo);
        }
        return ResultUtil.error(jsonObject.getStr("message"));
    }

    /**
     * 3.商品出库单接口：生成F22次品退厂单
     * A.参数：主单（包括：线上出库单号，出库仓库，供应商，出库类型，日期，备注），子单（包括：sku，数量，单价，备注等）
     * B.返回：单据是否同步成功的状态和线下单号。
     */
    public Result addOutDepot(OutDepot outDepot) {
        //System.out.println(JSONUtil.toJsonStr(new ErpRequestParams(access_token, outDepot)));
        String result = HttpRequest.post(erpServiceAddress + outDepotUrl)
                .body(JSONUtil.toJsonStr(new ErpRequestParams(access_token, outDepot)))
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("success") == 1) {
            ResultOutDepotVo resultVo = JSONUtil.toBean(jsonObject.getStr("obj"), ResultOutDepotVo.class);
            return ResultUtil.success(resultVo);
        }
        return ResultUtil.error(jsonObject.getStr("message"));
    }

    /**
     * 4.商品入库单接口：生成F22生产入库单
     * A.参数：主单（包括：线上入库单号，入库仓库，供应商，入库类型，日期，备注），子单（包括：sku，数量，单价，备注等）
     * B.返回：单据是否同步成功的状态和线下单号。
     */
    public Result addInDepot(InDepot inDepot) {
        String result = HttpRequest.post(erpServiceAddress + inDepotUrl)
                .body(JSONUtil.toJsonStr(new ErpRequestParams(access_token, inDepot)))
                .execute().body();
       // System.out.println(JSONUtil.toJsonStr(new ErpRequestParams(access_token, inDepot)));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        System.out.println(result);
        if (jsonObject.getInt("success") == 1) {
            ResultInDepotVo resultVo = JSONUtil.toBean(jsonObject.getStr("obj"), ResultInDepotVo.class);
            return ResultUtil.success(resultVo);
        }
        return ResultUtil.error(jsonObject.getStr("message"));
    }


    /**
     * 方法描述: erp全量同步商品
     *
     * @return void
     * @Author Small
     * @Date 2020/4/15 11:25
     * @param startTime
     * @param endTime
     */
    @SneakyThrows
    public void syncAllGoodFromErp(String startTime, String endTime) {
        // 分页大小
        int pageSize = PAGE_SIZE;
        if (EnvUtil.isDev()) {
            pageSize = 10;
        }
        // 起始页
        int startPage = 1;
        // 调用ERP系统拿到ERP的商品信息
        ResultStyleInfoVo erpStyleInfoByPage = erpStyleInfoByPage(startPage, pageSize, startTime, endTime);
        // 总条目
        int total = erpStyleInfoByPage.getTotal();
        // 总页码
        int totalPage = PageUtil.totalPage(total, pageSize);
        System.out.println(new ObjectMapper().writeValueAsString(erpStyleInfoByPage));
        // erp返回的数据
        List<StyleInfo> erpReturnData = erpStyleInfoByPage.getData();
        //进行ERP的商品信息的同步操作
        syncToGoods(erpReturnData);

        if (EnvUtil.isPro()) {
            if (startPage <= totalPage) {
                for (int i = 2; i <= totalPage; i++) {
                    // 调用ERP系统拿到ERP的商品信息
                    /*startPage += startPage;*/
                    ResultStyleInfoVo erpStyleInfoByPageLoop = erpStyleInfoByPage(i, pageSize,startTime,endTime);
                    // erp返回的数据
                    List<StyleInfo> erpReturnDataLoop = erpStyleInfoByPageLoop.getData();
                    //进行ERP的商品信息的同步操作
                    syncToGoods(erpReturnDataLoop);
                }
            }
        }

    }

    private void syncToGoods(List<StyleInfo> erpReturnData) {
        if (CollUtil.isNotEmpty(erpReturnData)) {
            erpReturnData.forEach(styleInfo -> {
                List<StyleSkuInfo> skus = styleInfo.getSkus();
                Goods goods = goodsService.selectByStyleNo(styleInfo.getStyleid());
                if (styleInfo.getStyleid().equals("LMIAW1043")) {
                    System.out.println("12312312312312312312312");
                }
                if (null == goods) {
                    Goods newGood = new Goods();
                    newGood.setGoodsName(styleInfo.getS_name());
                    newGood.setStyleNo(styleInfo.getStyleid());
                    newGood.setGoodsSn(styleInfo.getStyleid());
                    newGood.setMarketPrice(styleInfo.getJ_price());
                    newGood.setDiscountPrice(styleInfo.getX_price());
                  //  newGood.setStatus(GoodsStateEnum.GROUNDING.getValue());
                    newGood.setGsSeason(styleInfo.getSt_month());
                    newGood.setGsYear(styleInfo.getSt_year());
                    newGood.setStatus(GoodsStateEnum.UNDERCARRIAGE.getValue());
                    String st_type = styleInfo.getSt_type();
                    String dl_name = styleInfo.getDl_name();
                    String xz_name = styleInfo.getXz_name();
                    if (!StringUtil.isEmpty(st_type)) {

                        Category catLv1 = categoryService.selectByErpName(CAT_LV_1, st_type);
                        if (null == catLv1) {

                            // throw new BusinessException(StrUtil.format(CAT_ERR_MSG, "品类", st_type));
                        }
                        Category catLv2 = categoryService.selectByErpName(CAT_LV_2, dl_name);
                        if (null == catLv2) {
                            //throw new BusinessException(StrUtil.format(CAT_ERR_MSG, "大类", dl_name));
                        }
                        Category catLv3 = categoryService.selectByErpName(CAT_LV_3, xz_name);
                        if (null != catLv3) {
                            goods.setCatId(catLv3.getId());
                            goods.setCatName(catLv3.getCatName());
                            //throw new BusinessException(StrUtil.format(CAT_ERR_MSG, "小类", xz_name));
                        }
                        // 校验类目结构是否正确
                        if (catLv1 != null && catLv2 != null && catLv3 != null) {
                            String catPath = catLv1.getId() + "|" + catLv2.getId() + "|" + catLv3.getId();
                            if (!catPath.equals(catLv3.getCatPath())) {
                                String catPathV = catLv1.getCatName() + "|" + catLv2.getCatName() + "|" + catLv3.getCatName();
                                String erpCatPathV = st_type + "|" + dl_name + "|" + xz_name;
                                //throw new BusinessException(StrUtil.format(CAT_PATH_ERR_MSG, erpCatPathV, catPathV));
                            }
                        }

                    }
                    newGood.setGoodsFrom(GoodsFromEnum.ERP.getValue());
                    goodsService.save(newGood);
                    if (CollUtil.isNotEmpty(skus)) {
                        skus.forEach(styleSkuInfo -> {
                            Product product = new Product();
                            product.setGoodsId(newGood.getId());
                            product.setGoodsSn(newGood.getGoodsSn());
                            product.setProductSn(styleSkuInfo.getSku());
                            product.setStyleNo(newGood.getStyleNo());
                            product.setStatus(2);
                            // erp 颜色编号
                            String colorid = styleSkuInfo.getColorid();
                            String color = styleSkuInfo.getC_name();
                            // erp 尺码编号
                            String sizeid = styleSkuInfo.getSizeid();
                            String size = styleSkuInfo.getS_name();

                           /* SpecValueVo colorSpec = specValueService.selectSprcByErpId(COLOR_ID, colorid);
                            if (null == colorSpec) {
                                throw new BusinessException(StrUtil.format(COLOR_ERR_MSG, color, colorid));
                            }
                            SpecValueVo sizeSpec = specValueService.selectSprcByErpId(SIZE_ID, sizeid);
                            if (null == sizeSpec) {
                                throw new BusinessException(StrUtil.format(SIZE_ERR_MSG, size, sizeid));
                            }*/

                            SpecValueVo colorSpec = specValueService.selectSprcByErpId(COLOR_ID, colorid);
                            SpecValueVo sizeSpec = specValueService.selectSprcByErpId(SIZE_ID, sizeid);
                            if (colorSpec != null) {
                                SpecValue colorSpecParent = specValueService.getById(colorSpec.getParentId());
                                if (null != colorSpecParent) {
                                    colorSpec.setSpecName(colorSpecParent.getSpecValue());
                                    colorSpec.setSpecId(colorSpecParent.getId());
                                } else {
                                    colorSpec = null;
                                }

                            }

                            if (sizeSpec != null) {
                                SpecValue sizeSpecParent = specValueService.getById(sizeSpec.getParentId());
                                if (null != sizeSpecParent) {
                                    sizeSpec.setSpecName(sizeSpecParent.getSpecValue());
                                    sizeSpec.setSpecId(sizeSpecParent.getId());
                                } else {
                                    sizeSpec = null;
                                }
                            }
                            if (null != colorSpec && (null != sizeSpec)) {
                                product.setProductSku(wrapperSpec(colorSpec, sizeSpec));
                                product.setProductSkuDesp(wrapperSpecDesp(colorSpec, sizeSpec));
                                product.setProductName(styleInfo.getS_name());
                                product.setColor(colorSpec.getSpecValue());
                                product.setSize(sizeSpec.getSpecValue());
                                product.setMarketPrice(newGood.getMarketPrice());
                                product.setDiscountPrice(newGood.getDiscountPrice());
                                productService.save(product);
                            }

                           /* if (null == sizeSpec) {
                                throw new BusinessException(StrUtil.format(SIZE_ERR_MSG, size, sizeid));
                            }*/

                        });
                    }
                } else {
                    goods.setGoodsFrom(GoodsFromEnum.ERP.getValue());
                    goodsService.updateById(goods);
                    List<String> tt = goodsImgService.selectGoodsImg(goods.getId());
                    List<Product> products = productService.findByGoodsId(goods.getId());
                    for (StyleSkuInfo info : skus) {
                        boolean checkSku = checkSku(info, products);
                        if (checkSku) {
                            continue;
                        }
                        // 如果在系统中不存在就新增
                        Product product = new Product();
                        product.setGoodsId(goods.getId());
                        product.setGoodsSn(goods.getGoodsSn());
                        product.setStyleNo(goods.getStyleNo());
                        product.setProductSn(info.getSku());
                        if (tt != null && tt.size() > 0) {
                            product.setProductImg(tt.get(0));
                        }
                        // erp 颜色编号
                        String colorid = info.getColorid();
                        String color = info.getC_name();
                        // erp 尺码编号
                        String sizeid = info.getSizeid();
                        String size = info.getS_name();

                           /* SpecValueVo colorSpec = specValueService.selectSprcByErpId(COLOR_ID, colorid);
                            if (null == colorSpec) {
                                throw new BusinessException(StrUtil.format(COLOR_ERR_MSG, color, colorid));
                            }
                            SpecValueVo sizeSpec = specValueService.selectSprcByErpId(SIZE_ID, sizeid);
                            if (null == sizeSpec) {
                                throw new BusinessException(StrUtil.format(SIZE_ERR_MSG, size, sizeid));
                            }*/

                        SpecValueVo colorSpec = specValueService.selectSprcByErpId(COLOR_ID, colorid);
                        if (colorSpec != null) {
                            SpecValue colorSpecParent = specValueService.getById(colorSpec.getParentId());
                            if (null != colorSpecParent) {
                                colorSpec.setSpecName(colorSpecParent.getSpecValue());
                                colorSpec.setSpecId(colorSpecParent.getId());
                            } else {
                                colorSpec = null;
                            }

                        }
                        SpecValueVo sizeSpec = specValueService.selectSprcByErpId(SIZE_ID, sizeid);
                        if (sizeSpec != null) {
                            SpecValue sizeSpecParent = specValueService.getById(sizeSpec.getParentId());
                            if (null != sizeSpecParent) {
                                sizeSpec.setSpecName(sizeSpecParent.getSpecValue());
                                sizeSpec.setSpecId(sizeSpecParent.getId());
                            } else {
                                sizeSpec = null;
                            }
                        }
                        if (null != colorSpec && null != sizeSpec) {
                            product.setProductSku(wrapperSpec(colorSpec, sizeSpec));
                            product.setProductSkuDesp(wrapperSpecDesp(colorSpec, sizeSpec));
                            product.setProductName(styleInfo.getS_name());
                            product.setColor(colorSpec.getSpecValue());
                            product.setSize(sizeSpec.getSpecValue());
                            product.setMarketPrice(goods.getMarketPrice());
                            product.setDiscountPrice(goods.getDiscountPrice());
                            productService.save(product);
                        }

                    }
                }

            });
        }
    }

    private boolean checkSku(StyleSkuInfo info, List<Product> products) {
        for (Product pt : products) {

            if (info.getSku().equals(pt.getProductSn())) {
                return true;
            }
        }
        return false;
    }

    private String wrapperSpec(SpecValueVo colorSpec, SpecValueVo sizeSpec) {
        StringBuilder sb = new StringBuilder();
        sb.append(colorSpec.getSpecId())
                .append(":")
                .append(colorSpec.getId())
                .append(",")
                .append(sizeSpec.getSpecId())
                .append(":")
                .append(sizeSpec.getId());
        return sb.toString();
    }

    private String wrapperSpecDesp(SpecValueVo colorSpec, SpecValueVo sizeSpec) {
        StringBuilder sb = new StringBuilder();
        sb.append(colorSpec.getSpecName())
                .append(":")
                .append(colorSpec.getSpecValue())
                .append(",")
                .append(sizeSpec.getSpecName())
                .append(":")
                .append(sizeSpec.getSpecValue());
        return sb.toString();
    }

    /**
     * 方法描述: 从ERP同步数据
     *
     * @param indexPage
     * @return java.util.List<com.weixing.mall.provider.api.erp.entity.StyleInfo>
     * @Author Small
     * @Date 2020/4/15 10:50
     */
    private ResultStyleInfoVo erpStyleInfoByPage(int indexPage, int pageSize, String startTime, String endTime) {
        StyleQuery styleQuery = new StyleQuery();
        styleQuery.setPageindex(indexPage);
        styleQuery.setPagesize(pageSize);
        if (StringUtil.isNotEmpty(startTime)) {
            styleQuery.setStart_date(startTime);
        }
        if (StringUtil.isNotEmpty(endTime)) {
            styleQuery.setEnd_date(endTime);
        }
        ResultStyleInfoVo infoVo = selectStyleInfoByPage(styleQuery).getData();
        return infoVo;

    }

    /**
     * 方法描述: 按照货号检查ERP返回结果
     *
     * @param styleNo
     * @return com.weixing.mall.provider.api.erp.entity.StyleInfo
     * @Author sunshanwei
     * @Date 2020/12/7 10:50
     */
    public   ResultStyleInfoVo checkByStyleNo(String styleNo,String startTime,String endTime){

        StyleQuery styleQuery = new StyleQuery();
        styleQuery.setStyleid(styleNo);
        styleQuery.setPageindex(1);
        styleQuery.setPagesize(1);
        styleQuery.setStart_date(startTime);
        styleQuery.setEnd_date(endTime);
        ResultStyleInfoVo infoVo = selectStyleInfoByPage(styleQuery).getData();
        return infoVo;
    }
}
